<template>
  <el-dialog v-model="dialogVisible" :title="title" width="900">
    <el-form ref="formRef" v-loading="loading" :model="formData" :rules="rules" label-width="auto">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="配置列表" prop="configurations">
        <el-table :data="formData.configurations" border style="width: 100%">
          <el-table-column prop="weight" label="权重">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.weight"
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column prop="provider" label="供应商">
            <template #default="scope">
              <el-select v-model="scope.row.provider" placeholder="请选择">
                <el-option
                  v-for="item in providerList"
                  :key="item.id"
                  :label="item.providerName"
                  :value="item.providerName"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="配置状态" prop="configuration" width="100" align="center">
            <template #default="scope">
              <el-tag
                v-if="isEmpty(scope.row.configuration)"
                type="success"
                @click="handleGoSetConfig(scope.$index, scope.row)"
              >
                已配置
              </el-tag>
              <el-tag v-else type="danger" @click="handleGoSetConfig(scope.$index, scope.row)">
                点击配置
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="danger" link @click="handleDeleteConfig(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="width: 100%" :icon="Plus" @click="handleAddConfig">添加</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="loading" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import ProviderAPI from "@/api/virtual-number/provider.api"
import ProfileAPI from "@/api/virtual-number/profile.api"
import useToggle from "@/hooks/useToggle"
import { Plus } from "@element-plus/icons-vue"
const [loading, setLoading] = useToggle()
const [dialogVisible, setDialogVisible] = useToggle()

const emits = defineEmits(["refresh", "openConfigForm"])

const formData = ref({
  id: void undefined,
  name: "",
  configurations: [],
})

const title = computed(() => {
  return formData.value.id ? "编辑" : "新增"
})

const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
})

const formRef = ref(null)
const init = (row) => {
  setDialogVisible(true)

  nextTick(() => {
    formRef.value.resetFields()
    formData.value = { name: "", configurations: [] }
    if (row) formData.value = JSON.parse(JSON.stringify(row))
  })
}

const isEmpty = (data) => {
  if (Array.isArray(data)) return data.length > 0
  if (typeof data === "object") return Object.keys(data).length > 0
  return false
}

const handleGoSetConfig = (index, row) => {
  if (!formData.value.configurations[index].provider) return ElMessage.warning("请选择供应商")
  emits("openConfigForm", {
    index,
    row,
  })
}

const handleDeleteConfig = (index) => {
  if (Array.isArray(formData.value.configurations)) {
    return formData.value.configurations.splice(index, 1)
  }
}

const handleAddConfig = () => {
  if (Array.isArray(formData.value.configurations)) {
    return formData.value.configurations.push({
      weight: 0,
      provider: "",
      configuration: {},
    })
  }
  formData.value.configurations = [
    {
      weight: 0,
      provider: "",
      configuration: {},
    },
  ]
}

const setConfig = (index, data) => {
  if (Array.isArray(formData.value.configurations)) {
    return (formData.value.configurations[index].configuration = data)
  }
}

const providerList = ref([])
const getProviderList = async () => {
  const list = await ProviderAPI.getList({
    limit: 100,
    offset: 0,
  })
  providerList.value = list
}

const submit = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return
    setLoading(true)
    if (formData.value.id) {
      return ProfileAPI.update(
        {
          name: formData.value.name,
          configurations: formData.value.configurations,
        },
        formData.value.id
      )
        .then(() => {
          emits("refresh")
        })
        .finally(() => {
          handleClose()
          setLoading(false)
        })
    }

    ProfileAPI.create({
      name: formData.value.name,
      configurations: formData.value.configurations,
    })
      .then(() => {
        emits("refresh")
      })
      .finally(() => {
        handleClose()
        setLoading(false)
      })
  })
}

const handleClose = () => {
  setDialogVisible(false)
}

onMounted(() => {
  getProviderList()
})

defineExpose({
  init,
  setConfig,
})
</script>
